// src/components/DataViewer.js
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import {
  Table,
  Button,
  Input,
  Select,
  Space,
  Modal,
  Form,
  ColorPicker,
  message,
  Card,
  Tag,
  Tooltip,
  Checkbox,
  Row,
  Col,
  Typography,
  Popover,
  Breadcrumb,
} from 'antd';
import {
  CommentOutlined,
  PlusOutlined,
  SettingOutlined,
  HighlightOutlined,
  BgColorsOutlined,
  ArrowLeftOutlined,
  SaveOutlined,
  HistoryOutlined,
  DownloadOutlined,
  ExpandAltOutlined,
  UpOutlined,
  DownOutlined,
  EditOutlined,
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import CellContainer from './CellComponent';

const { Option } = Select;
const { TextArea } = Input;
const { Title, Text } = Typography;

function isHTML(str) {
  return typeof str === 'string' && /<[^>]+>/.test(str);
}

const DataViewer = () => {
  const { versionId } = useParams();
  const navigate = useNavigate();
  const [data, setData] = useState([]);
  const [headers, setHeaders] = useState([]);
  const [versionInfo, setVersionInfo] = useState(null);
  const [loading, setLoading] = useState(false);
  const [visibleColumns, setVisibleColumns] = useState([]);
  const [editingCell, setEditingCell] = useState(null);
  const [annotationModalVisible, setAnnotationModalVisible] = useState(false);
  const [addColumnModalVisible, setAddColumnModalVisible] = useState(false);
  const [columnSettingsVisible, setColumnSettingsVisible] = useState(false);
  const [selectedCell, setSelectedCell] = useState(null);
  const [annotations, setAnnotations] = useState({});
  const [form] = Form.useForm();
  const [columnForm] = Form.useForm();
  
  // 添加缺失的状态变量
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
  const [saveVersionModalVisible, setSaveVersionModalVisible] = useState(false);
  const [versionForm] = Form.useForm();
  const [previewModalVisible, setPreviewModalVisible] = useState(false);
  const [previewContent, setPreviewContent] = useState({ value: '', type: '', isHTML: false });
  const [rowPreviewModalVisible, setRowPreviewModalVisible] = useState(false);
  const [rowPreviewData, setRowPreviewData] = useState(null);
  const [isEditingPreview, setIsEditingPreview] = useState(false);
  const [previewEditValue, setPreviewEditValue] = useState('');
  const [modalTop] = useState(60);
  const [isResizing, setIsResizing] = useState(false);
  // 修改：行數據詳情彈窗每字段提供編輯按鈕，點擊後可單獨編輯
  const [rowPreviewEditing, setRowPreviewEditing] = useState({}); // { columnName: true/false }
  const [rowPreviewEditValues, setRowPreviewEditValues] = useState({}); // { columnName: value }

  const fetchData = useCallback(async (columns = null) => {
    setLoading(true);
    try {
      const params = columns ? { columns: columns.join(',') } : {};
      const response = await axios.get(`/api/versions/${versionId}/data`, { params });
      
      setData(response.data.data);
      setHeaders(response.data.headers);
      setVersionInfo(response.data.versionInfo);
      setVisibleColumns(columns || response.data.headers);
      
      // 处理批注数据
      const annotationMap = {};
      response.data.annotations.forEach(annotation => {
        const key = `${annotation.row_index}-${annotation.column_name}`;
        if (!annotationMap[key]) {
          annotationMap[key] = [];
        }
        annotationMap[key].push(annotation);
      });
      setAnnotations(annotationMap);
      
    } catch (error) {
      message.error('获取数据失败');
    } finally {
      setLoading(false);
    }
  }, [versionId]);

  useEffect(() => {
    if (versionId) {
      fetchData();
    }
  }, [versionId, fetchData]);

  // 键盘事件：空格键展开行预览
  useEffect(() => {
    const handleKeyDown = (e) => {
      // 只在没有其他弹窗时才响应空格
      if (
        previewModalVisible ||
        rowPreviewModalVisible ||
        annotationModalVisible ||
        addColumnModalVisible ||
        columnSettingsVisible ||
        saveVersionModalVisible
      ) {
        return;
      }
      if (e.code === 'Space' && selectedCell) {
        const row = data.find(r => r._rowIndex === selectedCell.rowIndex);
        if (row) {
          setRowPreviewData(row);
          setRowPreviewModalVisible(true);
        }
        e.preventDefault();
      }
    };
    window.addEventListener('keydown', handleKeyDown);

    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [
    selectedCell,
    data,
    previewModalVisible,
    rowPreviewModalVisible,
    annotationModalVisible,
    addColumnModalVisible,
    columnSettingsVisible,
    saveVersionModalVisible
  ]);

  // 使用useCallback缓存事件处理函数，避免不必要的重新渲染
  const handleCellEdit = useCallback(async (rowIndex, columnName, newValue) => {
    // 使用函数式更新来获取最新的data状态
    setData(currentData => {
      const rowData = currentData.find(row => row._rowIndex === rowIndex);
      const originalValue = rowData && rowData[columnName] ? rowData[columnName].value : '';
      
      // 标准化比较值（去除空格并转换为字符串）
      const normalizedOriginal = String(originalValue || '').trim();
      const normalizedNew = String(newValue || '').trim();
      
      // 如果值没有改变，直接退出编辑模式，不显示任何消息
      if (normalizedNew === normalizedOriginal) {
        setEditingCell(null);
        return currentData; // 返回原数据，不做修改
      }
      
      // 执行异步更新
      (async () => {
        try {
          await axios.put(`/api/versions/${versionId}/cell`, {
            rowIndex,
            columnName,
            value: newValue,
          });
          
          // 更新本地数据
          const newData = [...currentData];
          if (rowData) {
            rowData[columnName] = { ...rowData[columnName], value: newValue };
          }
          setData(newData);
          setEditingCell(null);
          setHasUnsavedChanges(true);

          message.success('更新成功');
        } catch (error) {
          message.error('更新失败');
          setEditingCell(null);
        }
      })();
      
      return currentData; // 暂时返回原数据
    });
  }, [versionId]);

  const handleCellClick = useCallback((rowIndex, columnName) => {
    setSelectedCell({
      rowIndex,
      columnName,
    });
  }, []);

  const handleCellDoubleClick = useCallback((rowIndex, columnName) => {
    setEditingCell(`${rowIndex}-${columnName}`);
  }, []);

  const handleExpandClick = useCallback((cellData, rowIndex, columnName) => {
    if (!cellData) return;
    setPreviewContent({
      value: cellData.value,
      type: cellData.type,
      isHTML: isHTML(cellData.value),
    });
    setPreviewModalVisible(true);
    // 新增：自动设置 selectedCell
    setSelectedCell({ rowIndex, columnName });
  }, []);

  const handleEditingCancel = useCallback(() => {
    setEditingCell(null);
  }, []);

  // 新增：行导航功能
  const handlePreviousRow = useCallback(() => {
    if (!rowPreviewData || !data.length) return;
    
    const currentIndex = data.findIndex(row => row._rowIndex === rowPreviewData._rowIndex);
    if (currentIndex > 0) {
      setRowPreviewData(data[currentIndex - 1]);
    }
  }, [rowPreviewData, data]);

  const handleNextRow = useCallback(() => {
    if (!rowPreviewData || !data.length) return;
    
    const currentIndex = data.findIndex(row => row._rowIndex === rowPreviewData._rowIndex);
    if (currentIndex < data.length - 1) {
      setRowPreviewData(data[currentIndex + 1]);
    }
  }, [rowPreviewData, data]);

  const getCurrentRowInfo = useCallback(() => {
    if (!rowPreviewData || !data.length) return { current: 0, total: 0, isFirst: true, isLast: true };
    
    const currentIndex = data.findIndex(row => row._rowIndex === rowPreviewData._rowIndex);
    return {
      current: currentIndex + 1,
      total: data.length,
      isFirst: currentIndex === 0,
      isLast: currentIndex === data.length - 1
    };
  }, [rowPreviewData, data]);

  // 新增：渲染行预览标题
  const renderRowPreviewTitle = () => {
    const { current, total, isFirst, isLast } = getCurrentRowInfo();
    
    return (
      <div style={{ display: 'flex', alignItems: 'center', width: '100%' }}>
        <span>行数据预览 ({current}/{total})</span>
        <Space style={{ marginLeft: '16px' }}>
          <Button
            type="text"
            icon={<UpOutlined />}
            onClick={handlePreviousRow}
            disabled={isFirst}
            size="small"
          >
            上一行
          </Button>
          <Button
            type="text"
            icon={<DownOutlined />}
            onClick={handleNextRow}
            disabled={isLast}
            size="small"
          >
            下一行
          </Button>
        </Space>
      </div>
    );
  };

  const handleEditPreview = () => {
    setIsEditingPreview(true);
    setPreviewEditValue(previewContent.value);
  };

  const handleSavePreview = async () => {
    if (!selectedCell) return;
    // 如果内容未修改，直接退出编辑模式
    if (previewEditValue === previewContent.value) {
      setIsEditingPreview(false);
      return;
    }
    try {
      await axios.put(`/api/versions/${versionId}/cell`, {
        rowIndex: selectedCell.rowIndex,
        columnName: selectedCell.columnName,
        value: previewEditValue,
      });
      // 更新本地数据
      setData(currentData => {
        const newData = [...currentData];
        const row = newData.find(r => r._rowIndex === selectedCell.rowIndex);
        if (row) {
          row[selectedCell.columnName] = { ...row[selectedCell.columnName], value: previewEditValue };
        }
        return newData;
      });
      setPreviewContent(prev => ({ ...prev, value: previewEditValue }));
      setIsEditingPreview(false);
      setHasUnsavedChanges(true);
      message.success('内容已保存');
    } catch (error) {
      message.error('保存失败');
    }
  };

  const handleCancelEditPreview = () => {
    setIsEditingPreview(false);
  };

  const renderPreviewContent = () => {
    const { value, type, isHTML: isHTMLContent } = previewContent;
    if (isEditingPreview) {
      return (
        <Input.TextArea
          value={previewEditValue}
          onChange={e => setPreviewEditValue(e.target.value)}
          rows={10}
        />
      );
    }
    if (isHTMLContent) {
      return <div dangerouslySetInnerHTML={{ __html: value }} />;
    }
    if (type === 'text') {
      return (
        <ReactMarkdown
          remarkPlugins={[remarkGfm]}
          components={{
            table: ({node, ...props}) => <table className="markdown-table" {...props} />
          }}
        >
          {value}
        </ReactMarkdown>
      );
    }
    return <pre style={{ whiteSpace: 'pre-wrap', wordBreak: 'break-word' }}>{value}</pre>;
  };

  // 新增：缺失的函数定义
  const showVersionHistory = useCallback(() => {
    if (versionInfo && versionInfo.file_id) {
      navigate(`/`); // 返回文件列表，用户可以查看版本历史
    }
  }, [navigate, versionInfo]);

  const handleAddAnnotation = async (values) => {
    try {
      await axios.post(`/api/files/${versionInfo.file_id}/annotation`, {
        rowIndex: selectedCell.rowIndex,
        columnName: selectedCell.columnName,
        content: values.content,
        color: values.color,
      });
      message.success('批注添加成功');
      setAnnotationModalVisible(false);
      form.resetFields();
      fetchData(visibleColumns);
    } catch (error) {
      message.error('添加批注失败');
    }
  };

  const handleAddColumn = async (values) => {
    try {
      await axios.post(`/api/versions/${versionId}/column`, {
        columnName: values.columnName,
        columnType: values.columnType,
        defaultValue: values.defaultValue,
      });
      message.success('列添加成功');
      setAddColumnModalVisible(false);
      columnForm.resetFields();
      fetchData();
    } catch (error) {
      message.error('添加列失败');
    }
  };

  const handleSaveAsNewVersion = async (values) => {
    try {
      const response = await axios.post(`/api/versions/${versionId}/save-new-version`, {
        submitter: values.submitter,
        changeDescription: values.changeDescription,
      });
      message.success('新版本保存成功');
      setSaveVersionModalVisible(false);
      versionForm.resetFields();
      setHasUnsavedChanges(false);
      // 可以选择跳转到新版本
      if (response.data.newVersionId) {
        navigate(`/data/${response.data.newVersionId}`);
      }
    } catch (error) {
      message.error('保存新版本失败');
    }
  };

  const handleRowPreviewEdit = (columnName, value) => {
    setRowPreviewEditing(prev => ({ ...prev, [columnName]: true }));
    setRowPreviewEditValues(prev => ({ ...prev, [columnName]: value }));
  };
  const handleRowPreviewEditChange = (columnName, value) => {
    setRowPreviewEditValues(prev => ({ ...prev, [columnName]: value }));
  };
  const handleRowPreviewEditSave = (rowIndex, columnName) => {
    const newValue = rowPreviewEditValues[columnName];
    handleCellEdit(rowIndex, columnName, newValue);
    setRowPreviewEditing(prev => ({ ...prev, [columnName]: false }));
  };
  const handleRowPreviewEditCancel = (columnName) => {
    setRowPreviewEditing(prev => ({ ...prev, [columnName]: false }));
  };

  const renderRowPreview = useCallback(() => {
    if (!rowPreviewData) return null;
    const rowIndex = rowPreviewData._rowIndex;
    return (
      <div style={{ maxHeight: 600, overflowY: 'auto', overflowX: 'hidden' }}>
        <Row gutter={[16, 16]}>
          {visibleColumns.map(columnName => {
            const cellData = rowPreviewData[columnName];
            const isEditing = rowPreviewEditing[columnName];
            const editValue = rowPreviewEditValues[columnName];
            const displayValue = cellData ? (typeof cellData.value === 'string' ? cellData.value : String(cellData.value)) : '';
            const isLongText = String(displayValue).length > 50;
            const contentRows = Math.max(3, String(displayValue).split('\n').length);
            return (
              <Col span={24} key={columnName}>
                <Card size="small" title={columnName}>
                  <div style={{ position: 'relative', minHeight: 60, padding: 8 }}>
                    {/* 内容区 */}
                    {isEditing ? (
                      <>
                        {isLongText ? (
                          <Input.TextArea
                            style={{ width: '100%', marginRight: 8 }}
                            value={editValue}
                            autoFocus
                            autoSize={{ minRows: contentRows, maxRows: 20 }}
                            onChange={e => handleRowPreviewEditChange(columnName, e.target.value)}
                            onPressEnter={e => { if (!e.shiftKey) handleRowPreviewEditSave(rowIndex, columnName); }}
                          />
                        ) : (
                          <Input
                            style={{ width: '100%', marginRight: 8 }}
                            value={editValue}
                            autoFocus
                            onChange={e => handleRowPreviewEditChange(columnName, e.target.value)}
                            onPressEnter={() => handleRowPreviewEditSave(rowIndex, columnName)}
                          />
                        )}
                        <Button type="primary" size="small" onClick={() => handleRowPreviewEditSave(rowIndex, columnName)} style={{ marginRight: 4 }}>保存</Button>
                        <Button size="small" onClick={() => handleRowPreviewEditCancel(columnName)}>取消</Button>
                      </>
                    ) : (
                      <>
                        <div
                          style={{
                            maxHeight: 200,
                            overflowY: 'auto',
                            overflowX: 'hidden',
                            paddingRight: 40,
                            wordBreak: 'break-all',
                            userSelect: 'text',
                            width: '100%',
                            maxWidth: 840,
                          }}
                          onDoubleClick={() => handleRowPreviewEdit(columnName, displayValue)}
                          title="双击可编辑"
                        >
                          {cellData ? (
                            isHTML(cellData.value) ? (
                              <div style={{whiteSpace: 'pre-wrap'}} dangerouslySetInnerHTML={{ __html: cellData.value }} />
                            ) : cellData.type === 'text' ? (
                              <div style={{whiteSpace: 'pre-wrap'}}>
                                <ReactMarkdown remarkPlugins={[remarkGfm]}>{cellData.value}</ReactMarkdown>
                              </div>
                            ) : (
                              displayValue
                            )
                          ) : <Text type="secondary">无数据</Text>}
                        </div>
                        {/* 右上角放大按钮 */}
                        <Button
                          size="small"
                          style={{
                            position: 'absolute',
                            right: 0,
                            top: 0,
                            zIndex: 3,
                            background: 'rgba(255,255,255,0.8)',
                            border: 'none',
                            boxShadow: 'none',
                          }}
                          icon={<ExpandAltOutlined />}
                          type="link"
                          title="放大查看"
                          onClick={e => {
                            e.stopPropagation();
                            if (cellData) handleExpandClick(cellData, rowIndex, columnName);
                          }}
                        />
                        {/* 右下角编辑按钮 */}
                        <Button
                          size="small"
                          style={{
                            position: 'absolute',
                            right: 0,
                            bottom: 0,
                            zIndex: 3,
                            background: 'rgba(255,255,255,0.8)',
                            border: 'none',
                            boxShadow: 'none',
                          }}
                          onClick={e => {
                            e.stopPropagation();
                            handleRowPreviewEdit(columnName, displayValue);
                          }}
                          icon={<EditOutlined />}
                          type="link"
                          title="编辑"
                        />
                      </>
                    )}
                  </div>
                </Card>
              </Col>
            );
          })}
        </Row>
      </div>
    );
  }, [rowPreviewData, visibleColumns, rowPreviewEditing, rowPreviewEditValues, handleExpandClick]);

  // 新增：AnnotationPopover 组件
  const AnnotationPopover = useCallback(() => {
    return (
      <div>
        <Button 
          type="primary" 
          size="small" 
          onClick={() => setAnnotationModalVisible(true)}
          style={{ marginBottom: 8, width: '100%' }}
        >
          添加批注
        </Button>
        <div>
          <Text type="secondary" style={{ fontSize: 12 }}>
            选中单元格: {selectedCell ? `行${selectedCell.rowIndex + 1}, ${selectedCell.columnName}` : '无'}
          </Text>
        </div>
      </div>
    );
  }, [selectedCell]);

  // 使用useMemo缓存columns配置，避免不必要的重新渲染
  const columns = useMemo(() => {
    return visibleColumns.map(columnName => ({
      title: columnName,
      dataIndex: columnName,
      key: columnName,
      width: 200,
      render: (cellData, record) => {
        const rowIndex = record._rowIndex;
        const cellKey = `${rowIndex}-${columnName}`;
        const cellAnnotations = annotations[cellKey] || [];
        const isSelected = selectedCell && 
          selectedCell.rowIndex === rowIndex && 
          selectedCell.columnName === columnName;
        const isEditing = editingCell === `${rowIndex}-${columnName}`;

        return (
          <CellContainer
            cellData={cellData}
            rowIndex={rowIndex}
            columnName={columnName}
            isSelected={isSelected}
            isEditing={isEditing}
            annotations={annotations}
            onCellClick={handleCellClick}
            onCellDoubleClick={handleCellDoubleClick}
            onCellEdit={handleCellEdit}
            onExpandClick={handleExpandClick}
            onEditingCancel={handleEditingCancel}
          />
        );
      },
    }));
  }, [
    visibleColumns, 
    annotations, 
    selectedCell, 
    editingCell, 
    handleCellClick, 
    handleCellDoubleClick, 
    handleCellEdit, 
    handleExpandClick, 
    handleEditingCancel
  ]);

  useEffect(() => {
    const handleKeyDown = (e) => {
      if (!selectedCell) return;

      let { rowIndex, columnName } = selectedCell;
      const colIdx = visibleColumns.indexOf(columnName);
      let changed = false;

      if (e.key === 'ArrowUp') {
        if (rowIndex > 0) { rowIndex -= 1; changed = true; }
      } else if (e.key === 'ArrowDown') {
        if (rowIndex < data.length - 1) { rowIndex += 1; changed = true; }
      } else if (e.key === 'ArrowLeft') {
        if (colIdx > 0) { columnName = visibleColumns[colIdx - 1]; changed = true; }
      } else if (e.key === 'ArrowRight') {
        if (colIdx < visibleColumns.length - 1) { columnName = visibleColumns[colIdx + 1]; changed = true; }
      } else {
        return;
      }

      if (changed) {
        setSelectedCell({ rowIndex, columnName });
        // 如果详情弹窗是打开且为阅读状态，自动切换详情内容
        if (previewModalVisible && !isEditingPreview) {
          const row = data.find(r => r._rowIndex === rowIndex);
          if (row && row[columnName]) {
            setPreviewContent({
              value: row[columnName].value,
              type: row[columnName].type,
              isHTML: isHTML(row[columnName].value),
            });
          }
        }
        e.preventDefault();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [selectedCell, data, visibleColumns, previewModalVisible, isEditingPreview]);

  useEffect(() => {
    if (!selectedCell) return;
    // 查找当前高亮单元格
    const cell = document.querySelector('.cell-container.selected-cell');
    if (cell) {
      cell.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });
    }
  }, [selectedCell]);

  return (
    <div>
      <Card>
        {/* 面包屑导航 */}
        <Breadcrumb style={{ marginBottom: 16 }}>
          <Breadcrumb.Item>
            <Button 
              type="link" 
              icon={<ArrowLeftOutlined />}
              onClick={() => navigate('/')}
              style={{ padding: 0 }}
            >
              文件列表
            </Button>
          </Breadcrumb.Item>
          <Breadcrumb.Item>数据查看</Breadcrumb.Item>
        </Breadcrumb>

        {/* 版本信息和操作按钮 */}
        {versionInfo && (
          <div style={{ marginBottom: 16 }}>
            <Row gutter={16} align="middle">
              <Col flex="auto">
                <Space>
                  <Title level={4} style={{ margin: 0 }}>
                    {versionInfo.original_name}
                  </Title>
                  <Tag color="blue">v{versionInfo.version}</Tag>
                  <Text type="secondary">
                    提交人: {versionInfo.submitter}
                  </Text>
                  <Text type="secondary">
                    {versionInfo.change_description}
                  </Text>
                  {hasUnsavedChanges && (
                    <Tag color="orange">有未保存的更改</Tag>
                  )}
                </Space>
              </Col>
              <Col>
                <Space>
                  {hasUnsavedChanges && (
                    <Button
                      type="primary"
                      icon={<SaveOutlined />}
                      onClick={() => setSaveVersionModalVisible(true)}
                    >
                      保存为新版本
                    </Button>
                  )}
                  <Button
                    icon={<HistoryOutlined />}
                    onClick={showVersionHistory}
                  >
                    版本历史
                  </Button>
                  <Button
                    icon={<PlusOutlined />}
                    onClick={() => setAddColumnModalVisible(true)}
                  >
                    添加列
                  </Button>
                  <Button
                    icon={<SettingOutlined />}
                    onClick={() => setColumnSettingsVisible(true)}
                  >
                    列设置
                  </Button>
                  {selectedCell && (
                    <Popover
                      content={<AnnotationPopover />}
                      title="添加批注"
                      trigger="click"
                    >
                      <Button icon={<CommentOutlined />}>
                        批注
                      </Button>
                    </Popover>
                  )}
                </Space>
              </Col>
            </Row>
          </div>
        )}

        {/* 表格 */}
        <Table
          columns={columns}
          dataSource={data}
          loading={loading}
          pagination={{
            pageSize: 50,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          scroll={{ x: 'max-content', y: 600 }}
          rowKey="_rowIndex"
          size="small"
        />
      </Card>

      {/* 批注模态框 */}
      <Modal
        title="添加批注"
        open={annotationModalVisible}
        onCancel={() => setAnnotationModalVisible(false)}
        onOk={() => form.submit()}
      >
        <Form form={form} onFinish={handleAddAnnotation} layout="vertical">
          <Form.Item name="type" label="批注类型" initialValue="comment">
            <Select>
              <Option value="comment">文字批注</Option>
              <Option value="highlight">高亮标记</Option>
              <Option value="background">背景颜色</Option>
            </Select>
          </Form.Item>
          
          <Form.Item
            noStyle
            shouldUpdate={(prevValues, currentValues) => 
              prevValues.type !== currentValues.type
            }
          >
            {({ getFieldValue }) => {
              const type = getFieldValue('type');
              
              if (type === 'comment') {
                return (
                  <Form.Item name="content" label="批注内容" rules={[{ required: true }]}>
                    <TextArea rows={4} />
                  </Form.Item>
                );
              }
              
              if (type === 'highlight') {
                return (
                  <>
                    <Form.Item name="backgroundColor" label="背景颜色" initialValue="#ffeb3b">
                      <ColorPicker />
                    </Form.Item>
                    <Form.Item name="textColor" label="文字颜色" initialValue="#000000">
                      <ColorPicker />
                    </Form.Item>
                  </>
                );
              }
              
              if (type === 'background') {
                return (
                  <Form.Item name="backgroundColor" label="背景颜色" initialValue="#e3f2fd">
                    <ColorPicker />
                  </Form.Item>
                );
              }
              
              return null;
            }}
          </Form.Item>
          
          <Form.Item name="createdBy" label="创建人" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>

      {/* 添加列模态框 */}
      <Modal
        title="添加新列"
        open={addColumnModalVisible}
        onCancel={() => setAddColumnModalVisible(false)}
        onOk={() => columnForm.submit()}
      >
        <Form form={columnForm} onFinish={handleAddColumn} layout="vertical">
          <Form.Item name="columnName" label="列名" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="columnType" label="列类型" initialValue="text">
            <Select>
              <Option value="text">文本</Option>
              <Option value="number">数字</Option>
              <Option value="date">日期</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 列设置模态框 */}
      <Modal
        title="列设置"
        open={columnSettingsVisible}
        onCancel={() => setColumnSettingsVisible(false)}
        onOk={() => {
          setColumnSettingsVisible(false);
          fetchData(visibleColumns);
        }}
        width={600}
      >
        <div>
          <Text strong>选择要显示的列：</Text>
          <div style={{ marginTop: 16, maxHeight: 400, overflowY: 'auto' }}>
            <Checkbox.Group
              value={visibleColumns}
              onChange={setVisibleColumns}
              style={{ width: '100%' }}
            >
              <Row>
                {headers.map(header => (
                  <Col span={8} key={header} style={{ marginBottom: 8 }}>
                    <Checkbox value={header}>{header}</Checkbox>
                  </Col>
                ))}
              </Row>
            </Checkbox.Group>
          </div>
        </div>
      </Modal>

      {/* 保存为新版本模态框 */}
      <Modal
        title="保存为新版本"
        open={saveVersionModalVisible}
        onCancel={() => setSaveVersionModalVisible(false)}
        onOk={() => versionForm.submit()}
      >
        <Form form={versionForm} onFinish={handleSaveAsNewVersion} layout="vertical">
          <Form.Item name="submitter" label="提交人" rules={[{ required: true }]}>
            <Input />
          </Form.Item>
          <Form.Item name="changeDescription" label="变更说明" rules={[{ required: true }]}>
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>

      {/* 内容预览模态框 */}
      <Modal
        title="内容预览"
        open={previewModalVisible}
        onCancel={() => { setPreviewModalVisible(false); setIsEditingPreview(false); }}
        footer={
          isEditingPreview ? (
            <>
              <Button onClick={handleCancelEditPreview}>取消</Button>
              <Button type="primary" onClick={handleSavePreview}>保存</Button>
            </>
          ) : (
            <Button onClick={handleEditPreview} disabled={!selectedCell}>编辑</Button>
          )
        }
        width={800}
        centered={false}
        maskClosable={false}
        modalRender={modal => <DraggableModal setIsResizing={setIsResizing}>{modal}</DraggableModal>}
      >
        <div>
          {renderPreviewContent()}
        </div>
      </Modal>

      {/* 行数据预览模态框 */}
      <Modal
        title={renderRowPreviewTitle()}
        open={rowPreviewModalVisible}
        onCancel={() => setRowPreviewModalVisible(false)}
        footer={null}
        width={1000}
      >
        {renderRowPreview()}
      </Modal>
    </div>
  );
};

export default DataViewer;

const DraggableModal = ({ children, setIsResizing }) => {
  const dragRef = React.useRef();
  const defaultWidth = 600, defaultHeight = 300, maxHeight = 800;
  const minWidth = 400, minHeight = 200; // 添加最小尺寸限制
  const [modalSize, setModalSize] = React.useState({ width: defaultWidth, height: defaultHeight });
  const resizingRef = React.useRef(false);

  // 遮罩事件攔截
  const addMaskBlocker = () => {
    const mask = document.querySelector('.ant-modal-root .ant-modal-mask');
    if (!mask) return;
    mask.__blocker = (e) => { e.stopPropagation(); e.preventDefault(); return false; };
    mask.addEventListener('mousedown', mask.__blocker, true);
    mask.addEventListener('click', mask.__blocker, true);
  };
  const removeMaskBlocker = () => {
    const mask = document.querySelector('.ant-modal-root .ant-modal-mask');
    if (!mask || !mask.__blocker) return;
    mask.removeEventListener('mousedown', mask.__blocker, true);
    mask.removeEventListener('click', mask.__blocker, true);
    delete mask.__blocker;
  };

  // 同步更新Modal内容高度
  React.useEffect(() => {
    const modal = dragRef.current;
    if (!modal) return;
    const content = modal.querySelector('.ant-modal-content');
    const body = modal.querySelector('.ant-modal-body');
    const footer = modal.querySelector('.ant-modal-footer');
    
    if (content) {
      content.style.height = `${modalSize.height}px`;
      content.style.overflow = 'hidden';
    }
    
    if (body) {
      // 计算body高度：总高度减去header和footer的高度
      const header = modal.querySelector('.ant-modal-header');
      const headerHeight = header ? header.offsetHeight : 55;
      const footerHeight = footer ? footer.offsetHeight : 53;
      const bodyHeight = Math.max(50, modalSize.height - headerHeight - footerHeight);
      body.style.height = `${bodyHeight}px`;
      body.style.overflowY = 'auto';
      body.style.padding = '16px';
      body.style.paddingBottom = `${footerHeight + 16}px`; // 为footer留出空间
      body.style.boxSizing = 'border-box';
    }
    
    // 确保footer始终可见
    if (footer) {
      footer.style.position = 'absolute';
      footer.style.bottom = '0';
      footer.style.left = '0';
      footer.style.right = '0';
      footer.style.zIndex = '1003';
      footer.style.background = '#fff';
      footer.style.borderTop = '1px solid #f0f0f0';
      footer.style.padding = '10px 16px';
    }
  }, [modalSize.height]);

  // 拖动位置逻辑
  React.useEffect(() => {
    const modal = dragRef.current;
    if (!modal) return;
    let isDown = false, startX = 0, startY = 0, startLeft = 0, startTop = 0;
    const header = modal.querySelector('.ant-modal-header');
    if (!header) return;
    header.style.cursor = 'move';
    const onMouseDown = (e) => {
      e.preventDefault();
      isDown = true;
      startX = e.clientX;
      startY = e.clientY;
      const rect = modal.getBoundingClientRect();
      startLeft = rect.left;
      startTop = rect.top;
      document.body.style.userSelect = 'none';
      document.body.style.cursor = 'move';
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    };
    const onMouseMove = (e) => {
      if (!isDown) return;
      const newLeft = startLeft + (e.clientX - startX);
      const newTop = startTop + (e.clientY - startY);
      modal.style.left = `${newLeft}px`;
      modal.style.top = `${newTop}px`;
      modal.style.margin = 0;
      modal.style.position = 'fixed';
    };
    const onMouseUp = () => {
      isDown = false;
      document.body.style.userSelect = '';
      document.body.style.cursor = '';
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    };
    header.addEventListener('mousedown', onMouseDown);
    return () => {
      header.removeEventListener('mousedown', onMouseDown);
      header.style.cursor = '';
      document.body.style.userSelect = '';
      document.body.style.cursor = '';
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    };
  }, []);

  // 拖拽放大，宽高都可放大，不能缩小到最小宽高
  React.useEffect(() => {
    const modal = dragRef.current;
    if (!modal) return;
    const content = modal.querySelector('.ant-modal-content');
    if (!content) return;
    let handle = content.querySelector('.resize-handle');
    if (!handle) {
      handle = document.createElement('div');
      handle.className = 'resize-handle';
      handle.style.position = 'absolute';
      handle.style.width = '16px';
      handle.style.height = '16px';
      handle.style.right = '0';
      handle.style.bottom = '0';
      handle.style.cursor = 'nwse-resize';
      handle.style.zIndex = '1004';
      handle.style.background = 'rgba(0,0,0,0.12)';
      handle.style.borderBottomRightRadius = '6px';
      handle.style.display = 'flex';
      handle.style.alignItems = 'flex-end';
      handle.style.justifyContent = 'flex-end';
      handle.style.pointerEvents = 'auto';
      handle.innerHTML = `<svg width="14" height="14" style="margin:1px;pointer-events:none"><polygon points="0,14 14,14 14,0" fill="#e0e0e0" /><line x1="4" y1="11" x2="11" y2="4" stroke="#888" stroke-width="1.5" /><line x1="8" y1="14" x2="14" y2="8" stroke="#888" stroke-width="1.5" /></svg>`;
      content.appendChild(handle);
    }
    let startX = 0, startY = 0, startW = 0, startH = 0;
    
    const onMouseMove = (e) => {
      if (!resizingRef.current) return;
      let deltaX = e.clientX - startX;
      let deltaY = e.clientY - startY;
      let newW = Math.max(minWidth, Math.min(window.innerWidth - 100, startW + deltaX));
      let newH = Math.max(minHeight, Math.min(maxHeight, startH + deltaY));
      setModalSize({ width: newW, height: newH });
    };
    const onMouseUp = () => {
      resizingRef.current = false;
      if (setIsResizing) setIsResizing(false);
      removeMaskBlocker();
      document.body.style.userSelect = '';
      document.body.style.cursor = '';
      window.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('mouseup', onMouseUp);
      window.removeEventListener('mouseleave', onMouseUp);
    };
    const onMouseDown = (e) => {
      e.stopPropagation();
      e.preventDefault();
      resizingRef.current = true;
      if (setIsResizing) setIsResizing(true);
      addMaskBlocker();
      startX = e.clientX;
      startY = e.clientY;
      startW = modal.offsetWidth;
      startH = modal.offsetHeight;
      document.body.style.userSelect = 'none';
      document.body.style.cursor = 'nwse-resize';
      window.addEventListener('mousemove', onMouseMove);
      window.addEventListener('mouseup', onMouseUp);
      window.addEventListener('mouseleave', onMouseUp);
    };
    handle.addEventListener('mousedown', onMouseDown);
    return () => {
      handle.removeEventListener('mousedown', onMouseDown);
      if (handle.parentNode) handle.parentNode.removeChild(handle);
      document.body.style.userSelect = '';
      document.body.style.cursor = '';
      window.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('mouseup', onMouseUp);
      window.removeEventListener('mouseleave', onMouseUp);
    };
  }, [setIsResizing]);

  return (
    <div
      ref={dragRef}
      style={{
        position: 'fixed',
        top: 60,
        left: `calc(50% - ${modalSize.width / 2}px)` ,
        zIndex: 1001,
        width: modalSize.width,
        height: modalSize.height,
        minWidth: minWidth,
        minHeight: minHeight,
        maxHeight,
        boxSizing: 'border-box',
        pointerEvents: 'auto',
      }}
    >
      {children}
    </div>
  );
};